package huffmantree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 构建哈夫曼树
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {13,7,8,3,29,6,1};
        Node huffmanTree = createHuffmanTree(arr);
        huffmanTree.preOrder();

    }
    //创建哈夫曼树
    public static Node createHuffmanTree(int[] arr){
        //遍历数组，将arr每个元素构成一个Node
        //将Node放入到ArrayList中
        ArrayList<Node> nodes = new ArrayList<Node>();
        for (int value: arr) {
            nodes.add(new Node(value));
        }

        while (nodes.size() >1){
            //排序（从小到大）
            Collections.sort(nodes);

            //取出根节点权值最小的两颗二叉树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            //构建一颗新的二叉树
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;

            //从ArrayList删除处理过的二叉树
            nodes.remove(leftNode);
            nodes.remove(rightNode);

            //将parent加入到ArrayList中
            nodes.add(parent);
        }
        //返回哈夫曼树的root节点
        return nodes.get(0);
    }
}

//创建节点
//为了让Node 对象持续排序Collections集合排序
//让Node实现Comparable接口
class Node implements Comparable<Node>{
    int value;  //节点权值
    Node left;
    Node right;

    //前序遍历
    public void preOrder(){
        System.out.println(this);
        if(this.left !=null){
            this.left.preOrder();
        }
        if(this.right !=null){
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    public int compareTo(Node o) {
        //表示从小到大排序
        return this.value - o.value;
    }
}
